<?php

namespace App\Http\Requests;

use App\Models\City;
use App\Models\MedicalRecord;
use App\Models\Patient;
use Illuminate\Database\Query\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class PatientBaseInfoRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     * @return bool
     */
    public function authorize()
    {
        return \Auth::check();
    }

    public function withValidator(Validator $validator)
    {
        $validator->after(function (Validator $validator) {
            if ($validator->messages()->isEmpty()) {
                $this->medicalNumber() ?: $validator->errors()->add('province', '病案号 已经存在。');
            }

            //            if ($validator->messages()->isEmpty()) {
            //                $this->cardNumber() ?: $validator->errors()->add('province', '身份证号 已经存在。');
            //            }

            if ($validator->messages()->isEmpty()) {
                $this->province() ?: $validator->errors()->add('province', '省份 不存在。');
            }

            if ($validator->messages()->isEmpty()) {
                $this->city() ?: $validator->errors()->add('city', '城市 不存在或不属于选择的省份。');
            }

            if ($validator->messages()->isEmpty()) {
                $this->county() ?: $validator->errors()->add('county', '区县 不存在或不属于选择的城市。');
            }

            if ($validator->messages()->isEmpty()) {
                !$this->phone() ?: $validator->errors()->add('exists', '该手机号已创建了首诊。');
            }
        });
    }

    public function phone()
    {
//        return MedicalRecord::where(['tn_user_base.phone' => $this->input('phone')])
//            ->join('tn_user_base', 'tn_user_base.id', '=', 'st_medical_records.patient_id')
//            ->exists();

        return MedicalRecord::where([
            'tn_user_base.phone' => $this->input('phone'),
            'st_medical_records.hospital_id' => $this->input('hospital_id'),
        ])
            ->join('tn_user_base', 'tn_user_base.id', '=', 'st_medical_records.patient_id')
            ->exists();
    }

    /**
     * 病案号
     * @return bool
     */
    protected function medicalNumber()
    {
        if ($this->has('medical_number')) {
            return !Patient::whereMedicalNumber($this->input('medical_number'))->exists();
        }

        return true;
    }

    //    protected function cardNumber()
    //    {
    //        if ($this->has('cardnumber')) {
    //            return !Patient::where('CARDNUMBER', $this->input('cardnumber'))->exists();
    //        }
    //
    //        return true;
    //    }

    protected function province()
    {
        $id = $this->input('province');

        if (empty($id)) {
            return true;
        }

        return City::where(['id' => $id])->count() ? true : false;
    }

    protected function city()
    {
        $id = $this->input('city');

        if (empty($id)) {
            return true;
        }

        return City::where(['id' => $id])->count() ? true : false;
    }

    protected function county()
    {
        $id = $this->input('county');

        if (empty($id)) {
            return true;
        }

        return City::where(['id' => $id])->count() ? true : false;
    }

    /**
     * Get the validation rules that apply to the request.
     * @return array
     */
    public function rules()
    {
        $rule = [
            'name'            => 'required|alpha_num|max:16',
            //  必填，手机号格式，唯一
            'phone'           => [
                'required',
                'regex:/^1(3|4|5|7|8|9)\\d{9}$/',
            ],
            'hospital_id'     => 'required|integer|min:1|exists:tn_scene,id',
            'doctor_id'       => [
                'required', 'integer', 'min:1',
                Rule::exists('tn_user_base', 'id')->where(function (Builder $query) {
                    $query->where('hospital_id', $this->input('hospital_id'));
                }),
            ],
            'sex'             => 'required|in:0,1',
            'birthday'        => 'required|date|before_or_equal:now',
            'clinic_at'       => 'date|before_or_equal:now',
            'medical_number'  => 'string|max:20',
            'cardnumber'      => 'string|max:20',
            'diabetes_type'   => 'in:1,2,3',
            'is_gestation'    => 'in:0,1,2',
            'special_illness' => 'in:0,1,2,3,4,5',
            'nation'          => 'integer|min:1|max:56',
            'province'        => ['integer', 'min:0'],
            'city'            => ['integer', 'min:0'],
            'county'          => ['integer', 'min:0'],
        ];

        if (!app('scene')->isWestern()) {
            $rule['diabetes_stage'] = 'required|in:' . implode(',', array_keys(config('custom.diabetes_stage.types')));
        }

        return $rule;
    }

    public function messages()
    {
        return [
            'name.required'             => '患者名称 必须填写。',
            'name.alpha'                => '患者名称 只能包含汉字、字母、数字。',
            'name.max'                  => '患者名称 最大 :max个字符。',
            'phone.required'            => '手机号码 必须填写。',
            'phone.regex'               => '手机号码 格式错误。',
            'phone.exists'              => '手机号码 已创建过病历。',
            'medical_number.max'        => '病案号 不能超过20个字符。',
            'doctor_id.exists'          => '该医院没有您选择的医生。',
            'clinic_at.date'            => '就诊日期格式不正确，例：1987-04-13。',
            'clinic_at.before_or_equal' => '就诊日期 必须要早于现在。',
            'birthday.required'         => '出生日期 必须要填写。',
            'birthday.date_format'      => '出生日期格式不正确，例：1987-04-13。',
            'birthday.before_or_equal'  => '出生日期 必须要早于现在。',
            'nation.integer'            => '民族 必须是整数。',
            'nation.min'                => '选择的民族 不存在。',
            'nation.max'                => '选择的民族 不存在。',
            'province.integer'          => '省份 必须是整数。',
            'province.min'              => '省份ID 需要大于等于 :min。',
            'city.integer'              => '城市 必须是整数。',
            'city.min'                  => '城市 需要大于等于 :min。',
            'county.integer'            => '区县 必须是整数。',
            'county.min'                => '区县 需要大于等于 :min。',
        ];
    }
}
